<?php
/**
 * This is the model class for table "category".
 *
 * The followings are the available columns in table 'category':
 * @property integer $id
 * @property string $name
 * @property integer $status
 * @property integer $parent
 */
class Category extends CActiveRecord{
    
    /*public $name;
    public $status;
    public $parent;
    */
    public static $tree = array();
    const ENABLE = 1;

    //validation data
    public function rules() {
        return array(
            array('name,status,parent','required'),
            array('name','length','min' => 4),
            array('id, name, status, parent', 'safe', 'on'=>'search'),
        );
    }
    
    /**
     * 
     */
    public function attributeLabels() {
        return array(
            'name' => 'Category name',
        );
    }
    
    /**
     * get children
     * @param type $id 
     */
    public static function getChildrend($id){
        $model = self::model();
        if($id != 0){
            self::$tree[$id]['data'] = $model->findByPk($id);
        }
        $children = $model->findAllByAttributes(array('parent' => $id,'status' => self::ENABLE));
        self::$tree[$id]['children'] = array();
        foreach($children as $child){
            self::$tree[$id]['children'][] = $child->id;
            self::getChildrend($child->id);
        }
    }

    /**
     * get tree category
     */
    public static function getTreeCategory(){
        if(count(self::$tree) > 0)
                return self::$tree;
        else{
            $object = new StdClass();
            $object->id = 0;
            $object->name = "root";
            self::$tree[0]['data'] = $object;
            self::getChildrend(0);
        }
        return self::$tree;
    }

    //get model
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
    //get table
    public function tableName()
    {
        return '{{category}}';
    }
}
